<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 总览表
 * Class Order
 */
class Order extends MY_Controller {
    /**
     * @var ConsumerOrderModel
     */
    public $mOrder = null;
    /**
     * @var MerchantUserModel
     */
    public $mMerchant = null;
    /**
     * @var consumerUserModel
     */
    public $mConsumer = null;

	public function __construct(){
		parent::__construct();
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->loadModel('consumerUserModel', 'mConsumer', 'consumer');
        $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');

	}
	
	/**
	 * 首页
	 */
	public function index(){

        $pay_type = $this->mOrder->PAY_TYPE;
        $status = $this->mOrder->status();
        unset($pay_type[0],$status['']);
        $s = date('Y-m-d', time());
        $startTime =  strtotime($s);
        $endTime =  strtotime('+1 day', $startTime);
        $endTime = dateFormat($endTime);
        $data = array(
            'timegap' => $s . ' - ' . $endTime,
            'merchant' => $this->mMerchant->getMerchantAll(),
            'pay_type' => $pay_type,
            'expense_type' => $this->mOrder->EXPENSE_TYPE,
            'status' => $status,
        );
		$this->view('statistics/order/index', $data, 'datatable,date_range_picker,select2');
	}

    public function getList(){
        $timeGap = trim(get('timegap'));
	    if ($timeGap){
            $timeGapArr = explode(' - ', $timeGap);
            $startTime = strtotime($timeGapArr[0]);
            $endTime = strtotime($timeGapArr[1]) + 86399;
        }else{
            $startTime =  strtotime(date('Y-m-d', time()));
            $endTime =  strtotime('+1 day', $startTime);
        }
//        p(dateFormat($startTime,true).'----'.dateFormat($endTime,true));
        $status = trim(get('status'));
        $pay_type = (int)get('pay_type');
        $expense_type = (int)get('expense_type');
        $url = '';
        if (!empty($status)) {
            $url = '&status=' . $status;
        }
        if ($pay_type){
            $url .= '&pay_type='.$pay_type;
        }
        if ($expense_type){
            $url .= '&expense_type='.$expense_type;
        }
        $data = $this->lists($startTime, $endTime);
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = $v['shop_name'];
            $data['aaData'][$k][] = $v['consumer'];
            $data['aaData'][$k][] = $v['total'];
            $data['aaData'][$k][] = sprintf('%.2f', $v['reality_amount']/$v['total']); //  单客价
            $data['aaData'][$k][] = $v['reality_amount'];
            $data['aaData'][$k][] = $v['service'];
            $data['aaData'][$k][] = isset($v['refund_amount']) ? $v['refund_amount'] : '0';
            $data['aaData'][$k][] = adminCreateBtn(array(
                'label' => '详情',
                'attr' => array(
                    'href' => getUrl('statistics/order/details?id='.$v['merchant_id'].'&stime='.$startTime.'&etime='.$endTime.$url),
                    'class' => 'btn green-stripe btn-xs default',
                    'target' => "_blank"
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'statistics',
                    'key' => 'order-view'
                )
            ));
        }
        unset($data['data']);
        echo json_encode($data);

    }

    /**
     * 明细
     */
    public function details(){
        $id = get('id');
        $sTime = get('stime');
        $eTime = get('etime');
        $status = trim(get('status'));
        $pay_type = (int)get('pay_type');
        $expense_type = (int)get('expense_type');
        if (!$id || !$sTime || !$eTime){
            show_404();
        }
        $time = dateFormat($sTime) . ' 至 '. dateFormat($eTime);
        $url = '?id='.$id.'&stime='.$sTime.'&etime='.$eTime;
        $merchant = $this->mMerchant->getInfo($id);
        $str = '';
        if (!empty($status)){
            $url .= '&status='.$status;
            $status = explode(',', $status);
            $str = '；状态：<i class="critical">';
            foreach ($status as $s){
                $str .= $this->mOrder->status($s).'、';
            }
            $str = trim($str, '、');
            $str .= '</i>';
        }
        if ($pay_type){
            $url .= '&pay_type='.$pay_type;
            $str .= '；支付方式：<i class="critical">'.$this->mOrder->PAY_TYPE[$pay_type] . '</i>';
        }
        if ($expense_type){
            $url .= '&expense_type='.$expense_type;
            $str .= '；消费模式：<i class="critical">'.$this->mOrder->EXPENSE_TYPE[$expense_type] . '</i>';
        }
        $data = array(
            'url' => $url,
            'time' => '商家：<i class="critical">'.$merchant['shop_name'].'</i>；时间区间：<i class="critical">' . $time .'</i>' . $str,
            'title' => '明细'
        );
        $this->view('statistics/order/details', $data, 'datatable,validation,region,select2');
    }

    public function detailsGetList(){
        $data = $this->detailsList();
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = '';
            $data['aaData'][$k][] = $v['id'];
            $data['aaData'][$k][] = $v['code'];
            $data['aaData'][$k][] = $v['mobile'];
            $data['aaData'][$k][] = $v['product_amount'];
            $shipping_fee = isset($v['shipping_fee']) ? $v['shipping_fee'] : 0;
            $data['aaData'][$k][] = $shipping_fee;
            $data['aaData'][$k][] = $v['total_amount'];
            $data['aaData'][$k][] = sprintf('%.2f',$v['total_amount']-$v['product_amount']); // 优惠金额
            $data['aaData'][$k][] = dateFormat($v['addtime'], true);
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 导出
     * @author defcu
     */
    public function export(){
        $timeGap = trim(get('timegap'));
        if ($timeGap){
            $timeGapArr = explode(' - ', $timeGap);
            $startTime = strtotime($timeGapArr[0]);
            $endTime = strtotime($timeGapArr[1]) + 86399;
        }else{
            $startTime =  strtotime(date('Y-m-d', time()));
            $endTime =  strtotime('+1 day', $startTime);
        }
        $filename = '总览表'.date('Y-m-d', time()).'.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo mb_convert_encoding('商家,下单用户量,订单总量,单客价,总金额,售后订单量,售后总额','gb2312','utf-8')."\n";
        $pageNumber = 500;
        $page = 1;
        while(true){
            $list = $this->lists($startTime, $endTime,$page,$pageNumber);
            if(empty($list)){
                break;
            }
            $page ++;
            foreach($list as $v){
                $reality_amount = sprintf('%.2f', $v['reality_amount']/$v['total']); //  单客价
                $refund_amount = isset($v['refund_amount']) ? $v['refund_amount'] : '0';
                echo mb_convert_encoding($v['shop_name'].','.$v['consumer'].','.$v['total']."\t".','.$reality_amount."\t".','.$v['reality_amount']."\t".','.$v['service']."\t".','.$refund_amount."\t", 'gb2312','utf-8')."\n";
            }
        }
        $ss = date('Y-m-d', $startTime);
        $ee = date('Y-m-d', $endTime);
        $status = trim(get('status'));
        $pay_type = (int)get('pay_type');
        $expense_type = (int)get('expense_type');
        $str = '';
        if (empty($status)){
            $status = explode(',', $status);
            $str = '；状态：';
            foreach ($status as $s){
                $str .= $this->mOrder->status($s).'、';
            }
            $str = trim($str, '、');
        }
        if ($pay_type){
            $str .= '；支付方式：'.$this->mOrder->PAY_TYPE[$pay_type];
        }
        if ($expense_type){
            $str .= '；消费模式：'.$this->mOrder->EXPENSE_TYPE[$expense_type];
        }
        echo mb_convert_encoding('时间区间：' . $ss .' - ' . $ee . $str, 'gb2312','utf-8')."\n";
    }

    /**
     * 导出详情
     */
    public function detailExport(){
        $filename = '总览表-订单详情'.date('Y-m-d',time()).'.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo mb_convert_encoding('订单id,订单号,会员手机,商品总价,物流价格,订单总价,订单优惠,下单日期','gb2312','utf-8')."\n";
        $pageNumber = 500;
        $page = 1;

        while(true){
            $data = $this->detailsList($page, $pageNumber);
            if(empty($data)){
                break;
            }
            $page ++;
            foreach($data as $v){
                $shipping_fee = isset($v['shipping_fee']) ? $v['shipping_fee'] : 0;
                $amount = sprintf('%.2f',$v['total_amount']-$v['product_amount']); // 优惠金额
                $addtime = dateFormat($v['addtime'], true);
                echo mb_convert_encoding($v['id']."\t".','.$v['code']."\t".','.$v['mobile']."\t".','.$v['product_amount']."\t".','.$shipping_fee.','.$v['total_amount'].','.$amount.','.$addtime, 'gb2312','utf-8')."\n";
            }
        }

        $id = get('id');
        $sTime = get('stime');
        $eTime = get('etime');
        $status = trim(get('status'));
        $pay_type = (int)get('pay_type');
        $expense_type = (int)get('expense_type');
        $time = dateFormat($sTime) . ' 至 '. dateFormat($eTime);
        $merchant = $this->mMerchant->getInfo($id);
        $str = '';
        if (!empty($status)){
            $status = explode(',', $status);
            $str = '；状态：';
            foreach ($status as $s){
                $str .= $this->mOrder->status($s).'、';
            }
            $str = trim($str, '、');
        }
        if ($pay_type){
            $str .= '；支付方式：'.$this->mOrder->PAY_TYPE[$pay_type];
        }
        if ($expense_type){
            $str .= '；消费模式：'.$this->mOrder->EXPENSE_TYPE[$expense_type];
        }
        echo mb_convert_encoding('商家：'.$merchant['shop_name'].'；时间区间：'.$time.$str, 'gb2312','utf-8')."\n";
    }

    /**
     * 平台资金信息
     * @param int $startTime        开始时间
     * @param int $endTime          结束时间
     * @param bool $isOne
     * @param int $page
     * @param int $pageNumber
     * @return array
     * @author heyu
     */
    public function lists($startTime = 0, $endTime = 0, $page = 0, $pageNumber = 0){
        $merchant = trim(get('merchant'));
        $status = trim(get('status'));
        $pay_type = (int)get('pay_type');
        $expense_type = (int)get('expense_type');

        if ($startTime){
            $this->db->where('o.addtime >= '.$startTime);
        }
        if ($endTime){
            $this->db->where('o.addtime < '.$endTime);
        }
        if (!empty($merchant)){
            $merchant = explode(',', $merchant);
            $this->db->where_in('o.merchant_id', $merchant);
        }
        if ($status){
            $status = explode(',', $status);
            if (in_array('6', $status)){
                $status[] = 7;
            }
            $this->db->where_in('o.status', $status);
        }
        if ($pay_type){
            $this->db->where('o.pay_type', $pay_type);
        }
        if ($expense_type){
            $this->db->where('o.expense_type', $expense_type);
        }
        $this->db->select('o.merchant_id,s.shop_name,count(DISTINCT o.consumer_id) AS consumer,
            count(o.id) AS total,sum(o.reality_amount) AS reality_amount,count(os.id) as service,
	        sum(os.refund_amount) as refund_amount')
            ->join($this->mMerchant->tbShop.' s', 's.merchant_id=o.merchant_id')
            ->join($this->mMerchant->tbUser.' m', 'm.id=o.merchant_id')
            ->join($this->mOrder->tbOrderService.' os', 'os.merchant_id=o.id and os.status=2', 'left')
            ->where('m.status > 1')
            ->group_by('o.merchant_id');

        if ($page && $pageNumber) {
            $tA = $this->mOrder->appPage($this->mOrder->tbOrder.' o', $page, false, $pageNumber);
            $tA = $tA['list'];
        }else{
            $tA = $this->mOrder->pagination($this->mOrder->tbOrder.' o');
        }
        return $tA;
    }

    /**
     * 根据时间获取订单明细列表
     * @param int $page
     * @param int $pageNumber
     * @return array
     */
    public function detailsList($page = 0, $pageNumber = 0){
        $id = get('id');
        $sTime = get('stime');
        $eTime = get('etime');
        $status = trim(get('status'));
        $pay_type = (int)get('pay_type');
        $expense_type = (int)get('expense_type');

        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"
        if ($status){
            $status = explode(',', $status);
            if (in_array('6', $status)){
                $status[] = 7;
            }
            $this->db->where_in('o.status', $status);
        }
        if ($pay_type){
            $this->db->where('o.pay_type', $pay_type);
        }
        if ($expense_type){
            $this->db->where('o.expense_type', $expense_type);
        }

        if ($iSortCol_0 == 1){
            $this->db->order_by('o.id', $sSortDir_0); // 订单id
        }else if($iSortCol_0 == 2){
            $this->db->order_by('o.code', $sSortDir_0); // 订单号
        }else if($iSortCol_0 == 4){
            $this->db->order_by('o.product_amount', $sSortDir_0); // 商品总价
        }else if($iSortCol_0 == 5){
            $this->db->order_by('o.shipping_fee', $sSortDir_0); // 物流价格
        }else if($iSortCol_0 == 6){
            $this->db->order_by('o.total_amount', $sSortDir_0); // 订单总价
        }else if($iSortCol_0 == 8){
            $this->db->order_by('o.addtime', $sSortDir_0); // 下单日期
        }else{
            $this->db->order_by('o.addtime desc'); // 下单日期
        }
        $this->db->select('o.id,o.code,u.mobile,o.product_amount,o.total_amount,o.reality_amount,
            o.shipping_fee,o.addtime')
            ->join($this->mConsumer->tbUser.' u', 'o.consumer_id=u.id')
            ->where(array('o.merchant_id' => $id))
            ->where('o.addtime >=', $sTime)
            ->where('o.addtime <', $eTime);
        if($page > 0 && $pageNumber > 0){
            $tA = $this->mOrder->appPage($this->mOrder->tbOrder.' o', $page, false, $pageNumber);
            return $tA['list'];
        }else{
            return $this->mOrder->pagination($this->mOrder->tbOrder.' o');
        }
    }
}
